package org.springframework.boot.netty.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.autoconfigure.netty.security.JwtToken;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;


public class JwtSecurityFilter implements ApplicationContextAware, SmartInitializingSingleton {

	private ApplicationContext applicationContext;

	private Boolean enableSecurity = false;

	private DefaultSecurityManager defaultSecurityManager;

	private final static Logger logger = LoggerFactory.getLogger(JwtSecurityFilter.class);

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}



	private void doAuthentication( Map<String,String> headers){
		String accessToken = headers.get("access_token")==null ? "" : headers.get("access_token");
		//获得当前用户到登录对象，现在状态为未认证
		Subject subject= SecurityUtils.getSubject();
		subject.login(new JwtToken(accessToken));
	}

	private void doLogout( ){
		//获得当前用户到登录对象，现在状态为已认证
		Subject subject= SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
			subject.logout();
		}
	}

	public void filterIfNessary(Map<String,String> headers){
		if(this.enableSecurity){
			//2.需要设置安全管理器
			SecurityUtils.setSecurityManager(this.defaultSecurityManager);
			doAuthentication(headers);
		}
	}

	public void logoutIfNessary(){
		if(this.enableSecurity){
			doLogout();
		}
	}

	@Override
	public void afterSingletonsInstantiated() {
		if(this.applicationContext.containsBean("shiroConfig")){
			this.enableSecurity = true;
			this.defaultSecurityManager = this.applicationContext.getBean(DefaultSecurityManager.class);
		}
	}
}
